<template>
  <view class="full-open-wrap">
    <!-- 头部 -->
    <nav-bar
      :title="details.activity_name || '爱玩满开'"
      :status="{
        type: title_status[details.open_type || 'refund'].type || 'refund',
        text: title_status[details.open_type || 'refund'].text || '',
      }"
      v-if="graduallyShow.top"
    ></nav-bar>

    <view class="good-main">
      <good-main
        :details="details"
        :current-box="currentBox"
        :total="boxTotal"
        v-if="graduallyShow.goodsMain"
      ></good-main>
      <view class="pick-num" v-if="graduallyShow.goodsList">
        <pick-num
          :timestamp="currentBox.open_status"
          :list="currentBox.choose_box"
          :total="currentBox.choose_box.all_total"
          @end="onTimestampEnd"
        ></pick-num>
      </view>
    </view>

    <view class="goods-group" v-if="graduallyShow.goodsList">
      <goods-group
        id="goodsgroup"
        :total="boxTotal"
        :current-box="currentBox"
        :probability="probabilitySwitch"
        @look="lookDetailsMod"
        v-if="graduallyShow.goodsList"
      ></goods-group>
    </view>

    <view class="bottom-btn" v-if="graduallyShow.lotteryShow">
      <fullopen-btn @operate="onFullopenBtn"></fullopen-btn>
    </view>
    <!--  -->
    <view class="timeout" v-if="showTimeOver">
      <view class="time-card">
        <image class="img-time" :src="timeOver" />
        <view class="time-content">
          <view
            class="know-btn"
            hover-class="hover-bubble"
            @tap="onShowKnowTimerOver"
          >
            <image mode="widthFix" :src="timeKnow" alt="" />
          </view>
        </view>
      </view>
    </view>
    <!-- 额外按钮 -->
    <other-btn
      @other-btn="onOtherBtn"
      v-if="graduallyShow.borderButtonDis"
    ></other-btn>
    <!-- 展开按钮 -->
    <unfold-btn
      :active-id="initiallyId"
      @unfold="onUnfold"
      v-if="graduallyShow.borderButtonDis"
    ></unfold-btn>
    <!-- 箱子列表 -->
    <box-list
      v-if="boxListModuleStauts"
      :initially-id="initiallyId"
      :current-box="currentBox"
      :total="boxTotal"
      :rows="boxRows"
      @change-box-list-mod="changeBoxListMod"
      @select="selectBox"
    ></box-list>
    <!-- 开奖记录 -->
    <lottery-history
      v-if="lotteryHistoryOpen"
      :initially-id="initiallyId"
      :box-id="currentBox.box_id"
      @change-history-mod="changeHistoryMod"
    ></lottery-history>
    <!-- 开奖结果 -->
    <view :hidden="!lotteryResultOpen">
      <lottery-result
        :show="lotteryResultOpen"
        :result="lotteryResultList"
        :number="continueToDrawNum"
        @continue="onResultContinue"
        @keep="onResultKeep"
        @next="onResultNext"
      ></lottery-result>
    </view>
    <!-- 选盒 -->
    <select-box
      v-if="showSelectBoxOpen"
      :initially-id="initiallyId"
      :box-id="currentBox.box_id"
      @show-select-box-mod="showSelectBoxMod"
      @operate="onSelectBoxOperate"
    ></select-box>
    <!-- 规则 -->
    <rules
      :details="explain"
      v-if="explainOpen"
      @change-rules-mod="changeRulesMod"
    ></rules>
    <!-- 支付 -->
    <shopro-pay-model
      :history="payHistory"
      @change-pay-mod="changePayMod"
      @result="onDrawResults"
      @payed="onPayed"
      v-if="showTrade"
      activity-type="full_open"
      :protocol="initiallyId"
      :details="payDetails"
    ></shopro-pay-model>
    <!-- 款式详情 -->
    <shoprodetails
      :product-id="productId"
      @change-details-mod="changeDetailsMod"
      v-if="productDetails"
    ></shoprodetails>
    <!-- 分享 -->
    <shopro-share v-model="showShare" posterType="user"></shopro-share>
    <!-- 登录提示 -->
    <shopro-auth-modal></shopro-auth-modal>
  </view>
</template>
<script>
import timeOver from './img/time-1251.png';
import timeKnow from './img/know-10.png';
import share from '@/shopro/share';
import { EXTRACTABLEE } from './fullOpen_config';
import OtherBtn from './components/other-btn.vue';
import GoodMain from './components/good-main.vue';
import NavBar from './components/navbar.vue';
import LotteryHistory from './components/lottery-history.vue';
import Rules from './components/rules.vue';
import UnfoldBtn from './components/unfold-btn.vue';
import BoxList from './components/box-list.vue';
import PickNum from './components/pick-num.vue';
import GoodsGroup from './components/goods-group.vue';
import FullopenBtn from './components/fullopen-btn.vue';
import SelectBox from './components/select-box.vue';
import LotteryResult from './components/lottery-result.vue';
 import shoprodetails from './components/shopro-commodity-details/shopro-commodity-details.vue';
export default {
  // 建议 创建每个组件时 都添加name属性 标识组件名称
  name: '',
  components: {
	  shoprodetails,
    NavBar,
    GoodMain,
    OtherBtn,
    LotteryHistory,
    Rules,
    UnfoldBtn,
    BoxList,
    PickNum,
    GoodsGroup,
    FullopenBtn,
    SelectBox,
    LotteryResult,
  },
  data() {
    return {
      timeKnow,
      timeOver,
      // 全局视图展示开关
      graduallyShow: {
        // 顶部展示
        top: false,
        // 商品列表展示
        goodsList: false,
        // 商品主体展示
        goodsMain: false,
        // 额外按钮展示
        borderButtonDis: false,
        // 抽奖按钮区展示
        lotteryShow: false,
      },
      initiallyId: '',
      //当前查看商品id
      productId: '',
      //当前商品信息
      details: {},
      // 当前箱子
      currentBox: {
        // 箱子状态
        status: 1,
        // 箱子id
        box_id: 0,
        // 当前箱子位置
        index: 0,
        //箱子内 商品列表
        box_goods: {
          list: [],
          //商品总数
          total: 0,
        },
        // 商品库存
        box_num: {
          // 总库存
          total: 0,
          // 当前箱子内 剩余商品数量
          surplus: 0,
        },
        //箱子顺序
        box_sort: {
          // 当前总箱子数
          count: 0,
          // 当前箱子数
          sort: 0,
        },
        // 已选盒号
        choose_box: {
          chose_list: [],
          chose_total: 0,
          all_total: 0,
        },
        // 开奖时间
        open_status: {
          status: '',
          text: '',
          time: 0,
        },
      },
      // 箱子数量
      boxTotal: 0,
      //箱子区间数
      boxRows: 4,
      boxOperate: {},
      /**
       * 箱子列表
       * [
       * [],
       * [],
       * [],
       * [],
       * ]
       *
       */
      boxList: [],
      // // 已选盒号
      // chooseBoxs: {
      //   chose_list: [],
      //   list: [],
      //   box_cover_image: '',
      // },
      //结果列表
      lotteryResultList: {},
      //说明
      explain: '',
      // 交易信息
      payDetails: {},
      payHistory: {
        type: '',
      },
      extractable: EXTRACTABLEE,

      title_status: {
        open: {
          type: 'on',
          text: '到点开奖',
        },
        refund: {
          type: 'over',
          text: '到点退款',
        },
      },
      // 可开奖数 测试 1 默认0
      continueToDrawNum: 1,
      // 音效开启关闭
      soundOpen: true,
      // 中奖纪录显示隐藏
      winningRecordOpen: false,
      // 规则展示隐藏
      rulesOpen: false,
      // 支付展示
      paymentOpen: false,
      // 箱子列表弹窗显示
      boxListModuleStauts: false,
      // 抽奖 结果展示
      lotteryResultOpen: false,
      // 开奖纪录展示
      lotteryHistoryOpen: false,
      // 规则显示隐藏
      explainOpen: false,
      //分享 显示隐藏
      showShare: false,
      // 交易弹窗
      showTrade: false,
      // 查看款式详情
      productDetails: false,
      // 显示隐藏 选盒
      showSelectBoxOpen: false,
      // 时间已到
      showTimeOver: false,
    };
  },
  // 计算属性 适配者模式
  computed: {
    // 概率显示隐藏
    probabilitySwitch() {
      let type = this.details?.probability_switch || '0';
      return type == '1' ? true : false;
    },
  },
  // 数据监听
  watch: {},
  /**
   * 生命周期 类似 发布订阅者模式
   */
  //监听页面初始化，其参数同 onLoad 参数 触发时机早于 onLoad 百度小程序
  //onInit() {},
  /** 监听页面加载
   * 其参数为上个页面传递的数据，
   * 参数类型为 Object（用于页面传参）
   */
  onLoad(e = {}) {
    let { title, id, box_id } = e;
    this.initiallyId = this.$Route.query?.id || id || '';
    this.currentBox.box_id = box_id || 0;
    this.globalGraduallyShow();
  },
  // 监听页面显示。页面每次出现在屏幕上都触发 包括从下级页面点返回露出当前页面
  onShow() {},
  // 监听页面初次渲染完成 注意如果渲染速度快，会在页面进入动画完成前触发
  onReady() {},
  // 监听页面隐藏
  onHide() {},
  // 监听页面卸载
  onUnload() {},
  methods: {
    // 对应的执行顺序请求数据
    orderOfExecution() {
      /***
       * 箱子请求操控
       * 初次进来
       * 1 获取 满开 信息
       * 2 获取箱子总数
       * 3 获取箱子列表
       * 4 获取当前箱子详情
       */

      return {
        top: null,
        lotteryShow: null,
        borderButtonDis: null,
        // 获取 商品列表
        goodsList: () => {
          const tim0 = new Date().getTime();
          return new Promise((resolve, reject) => {
            this.getBoxTotal()
              .then(() => {
                return this.getBoxDetails({
                  box_id: this.currentBox.box_id,
                });
              })
              .then(() => {
                const tim1 = new Date().getTime();
                resolve({ time: tim1 - tim0 });

                // return this.getChooseBoxs();
              })
              // .then(() => {
              //   const tim1 = new Date().getTime();
              //   resolve({ time: tim1 - tim0 });
              // })
              .catch(() => {
                const tim1 = new Date().getTime();
                reject({ time: tim1 - tim0 });
              });
          });
        },
        // 商品主体
        goodsMain: () => {
          const tim0 = new Date().getTime();
          return new Promise((resolve, reject) => {
            this.getDetails()
              .then(() => {
                const tim1 = new Date().getTime();
                resolve({ time: tim1 - tim0 });
              })
              .catch(() => {
                const tim1 = new Date().getTime();
                reject({ time: tim1 - tim0 });
              });
          });
        },
      };
    },

    // 渐序展示视图
    globalGraduallyShow() {
      // 执行列表
      const eventList = this.orderOfExecution();
      // 组件渲染延迟 函数
      const fn = (_ev = () => {}, delay = 400) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            _ev();
            resolve(true);
          }, delay);
        });
      };
      // 视图列表
      const views = Object.keys(this.graduallyShow);
      const len = views.length;

      return new Promise(async (resolve, reject) => {
        // 按顺序 依次执行
        for (let i = 0; i < len; i++) {
          const item = views[i];
          // 延迟800ms
          let t = 60;
          if (eventList[item]) {
            // 请求
            try {
              let result = await eventList[item]();
              // 请求异步 耗时 耗时大于60ms直接渲染 小于60ms异步差值 渲染
              t = result.time > 60 ? 0 : 60 - result.time;
            } catch (error) {
              t = error.time > 60 ? 0 : 60 - error.time;
            }
          }
          // 执行 延迟函数
          const timeout = await fn(() => {
            // 渲染
            this.$set(this.graduallyShow, item, true);
            // // 获取商品主体高度
            // if (item == 'goodsMain') {
            //   this.getGroupMain();
            // }
            if (i == len - 1) {
              resolve();
            }
          }, t);
        }
      });
    },
    getBoxTotal() {
      return new Promise((resolve, reject) => {
        this.$http(
          'v1.getFullOpenBoxsAction',
          {
            id: this.initiallyId,
            action: 'total',
          },
          '加载中...'
        ).then((res) => {
          if (res.code === 1) {
            this.boxTotal = res.data?.count || res.data || 1;
            resolve();
          } else {
            reject();
          }
        });
      });
    },
    getBoxDetails(ev = {}) {
      let { status = 'init', box_id = '0' } = ev;
      return new Promise((resolve, reject) => {
        this.$http(
          'v1.getFullOpenBoxs',
          {
            id: this.initiallyId,
            box_id,
          },
          '加载中'
        ).then((res) => {
          if (res.code === 1) {
            this.currentBox.index = res.data?.box_sort?.sort;
            this.currentBox = Object.assign(this.currentBox, res.data);
            Object.keys(this.currentBox.price).forEach((item) => {
              const ele = this.currentBox.price[item];
              this.$set(this.extractable[item], 'price', ele);
            });
            if (res.data?.open_status?.time == 0) {
              this.onTimestampEnd(0);
            }

            resolve();
          } else {
            uni.showModal({
              title: '爱玩满开',
              content: res.msg,
            });
            reject();
          }
        });
      });
    },
    // 获取商品信息
    getDetails() {
      return new Promise((resolve, reject) => {
        this.$http(
          'v1.getFullOpen',
          {
            id: this.initiallyId,
          },
          '加载中...'
        ).then((res) => {
          if (res.code === 1) {
            this.details = res.data;
            share.setShareInfo({
              title: this.details.activity_name,
              desc: '',
              image: this.details.cover_image,
              params: {
                page: 5,
                pageId: this.initiallyId,
              },
            });

            //获取 箱子总数
            resolve();
          } else {
            reject();
          }
        });
      });
    },

    //监听右上角自定义按钮
    onOtherBtn(ev) {
      switch (ev.name) {
        case 'look':
          this.getRules().then(() => {
            this.explainOpen = true;
          });

          break;
        case 'share':
          share.setShareInfo({
            title: this.details.activity_name,
            desc: '',
            image: this.details.cover_image,
            params: {
              page: 5,
              pageId: this.initiallyId,
            },
          });

          this.showShare = true;
          break;
        case 'live':
          break;
        case 'test':
          this.lotteryResultOpen = true;
          break;
        case 'up':
          let content = '';
          if (this.allSkip) {
            content = '是否需要开启抽奖动画';
          } else {
            content = '是否需要跳过抽奖动画';
          }
          uni.showModal({
            title: '抽奖动画',
            content,
            showCancel: true,
            cancelText: '取消',
            confirmText: '确定',
            success: (result) => {
              if (result.confirm) {
                this.changeAllSkip(!this.allSkip);
              }
            },
            fail: () => {},
            complete: () => {},
          });

          break;
      }
    },
    onFullopenBtn(ev) {
      switch (ev.data.id) {
        case 'switch':
          this.changeBoxListMod(true);
          break;
        case 'select':
          this.showSelectBoxMod(true);
          break;
      }
    },
    // 获取规则
    getRules() {
      return new Promise((resolve, reject) => {
        if (this.explain) {
          resolve();
          return;
        }
        this.$http(
          'v1.activitysDetails',
          {
            activity_id: this.initiallyId,
            type: 'full_open',
          },
          '加载中'
        ).then((res) => {
          if (res.code === 1) {
            this.explain = res.data?.content || '';
            resolve();
          } else {
            reject();
          }
        });
      });
    },
    // 显示隐藏 商品详情
    changeDetailsMod(ev) {
      this.productId = '';
      this.productDetails = ev;
    },
    // 监听选择盒子 购买
    onSelectBoxOperate(ev) {
      let params = {
        activity_type: 'full_open',
        activity_id: this.initiallyId,
        box_id: this.currentBox.box_id,
      };
      if (ev.mode.id == 'confrim') {
        params.roll_num = ev.selected.length;
        params.choose_boxs = ev.selected.join(',');
        this.boxOperate = ev;
      } else {
        params.roll_num = 'all';
      }
      this.$http('v1.createOrder', params, '正在创建').then((res) => {
        if (res.code === 1) {
          this.payDetails = {
            ...res.data,
          };
          this.showTrade = true;
        }
      });
    },
    // 待开奖倒计时结束
    onTimestampEnd(ev) {
      this.getFullOpenResult();
    },
    // 时间到了
    onShowKnowTimerOver() {
      this.showTimeOver = false;
    },
    // 查询用户是否有满开开奖结果未查看
    getFullOpenResult() {
      this.$http('v1.getfullOpenRes', {}).then((res) => {
        if (res.code === 1) {
          if (res.data.total > 0) {
            this.continueToDrawNum = res.data.total;
            let boxRes = res.data.list[0];
            this.initiallyId = boxRes.activity_id;
            this.getBoxTotal()
              .then(() => {
                return this.getBoxDetails({
                  box_id: boxRes.box_id,
                });
              })
              .then(() => {
                return this.getDetails();
              })
              .then(() => {
                return this.$http('v1.getfullOpenBoxsopenRes', {
                  id: this.initiallyId,
                  box_id: this.currentBox.box_id,
                });
              })
              .then((res) => {
                if (res.code === 1 && res.data.open_status == 1) {
                  this.lotteryResultList = res.data;
                  this.lotteryResultOpen = true;
                } else {
                  this.showTimeOver = true;
                }
              })
              .catch(() => {});
          }
        }
      });
    },
    // 关闭 交易弹窗
    changePayMod(e) {
      this.showTrade = e;
      this.payDetails = {};
    },
    // 结果
    onDrawResults(ev) {
      // this.lotteryResultOpen = true;
      this.showTrade = false;
      this.showSelectBoxOpen = false;
    },
    // 支付后的结果
    onPayed(ev) {
      this.payHistory = { type: ev.type };
      let param = {
        id: this.initiallyId,
        order_sn: ev.result.data.order_sn,
        box_id: this.currentBox.box_id,
      };
      if (this.boxOperate?.mode?.id == 'confrim') {
        param.roll_num = this.boxOperate.selected.length;
        param.choose_boxs = this.boxOperate.selected.join(',');
      } else {
        params.roll_num = 'all';
      }

      // 抽奖
      this.$http('v1.getfullOpenRoll', param, '请稍等').then((res) => {
        if (res.code === 1) {
          this.onDrawResults(res.data);
          this.boxOperate = {};
          uni.showModal({
            title: '爱玩满开',
            content: '购买成功',
          });
          this.getBoxTotal()
            .then(() => {
              return this.getBoxDetails({
                box_id: this.currentBox.box_id,
              });
            })
            .then(() => {
              return this.getDetails();
            })
            .then(() => {})
            .catch(() => {});
        }
      });
    },
    // 规则显示隐藏
    changeRulesMod(e) {
      this.explainOpen = e;
    },
    // 开奖记录展示隐藏
    changeHistoryMod(e) {
      this.lotteryHistoryOpen = e;
    },
    // 监听 扩展按钮 事件
    onUnfold(e) {
      switch (e.type) {
        //音效
        case 'noise':
          break;
        // 开奖记录
        case 'history':
          this.changeHistoryMod(e.status);
          break;
        // 盒柜
        case 'cabinet':
          break;
        // 刷新
        case 'refresh':
          uni.showLoading({
            title: '刷新中',
            mask: true,
          });
          this.globalGraduallyShow().then(() => {
            uni.hideLoading();
          });
          break;
      }
    },
    // 继续开奖
    onResultContinue() {
      this.lotteryResultOpen = false;
      this.getFullOpenResult();
    },
    // 开心收下
    onResultKeep() {
      this.lotteryResultOpen = false;
      this.getBoxTotal()
        .then(() => {
          return this.getBoxDetails({
            box_id: this.currentBox.box_id,
          });
        })
        .then(() => {
          return this.getDetails();
        })
        .then(() => {})
        .catch(() => {});
    },
    // 下一页
    onResultNext() {},

    // 箱子列表展示隐藏
    changeBoxListMod(e) {
      this.boxListModuleStauts = e;
    },
    // 选择箱子
    selectBox(ev) {
      this.getBoxDetails({
        action: 'selected',
        box_id: ev.item.box_id,
      })
        .then(() => {})
        .catch(() => {});
    },
    // 查看 商品详情
    lookDetailsMod(ev) {
      this.productId = ev;
      this.productDetails = true;
    },
    // 显示隐藏 选盒模态框
    showSelectBoxMod(ev) {
      this.showSelectBoxOpen = ev;
    },
  },
  /** ---------- */
  // 监听窗口尺寸变化 App、微信小程序、快手小程序
  //onResize() {},
  // 监听用户下拉动作，一般用于下拉刷新
  //onPullDownRefresh() {},
  // 页面滚动到底部的事件（不是scroll-view滚到底），常用于下拉下一页数据
  //onReachBottom() {},
  //点击 tab 时触发，参数为Object 微信小程序、QQ小程序、支付宝小程序、百度小程序、H5、App、快手小程序、京东小程序
  //onTabItemTap() {},
  //用户点击右上角分享 微信小程序、QQ小程序、支付宝小程序、字节小程序、飞书小程序、快手小程序、京东小程序
  //onShareAppMessage() {},
  //监听页面滚动 nvue暂不支持
  //onPageScroll() {},
  //监听原生标题栏按钮点击事件 App、H5
  //onNavigationBarButtonTap() {},
  /** 监听页面返回
   * 返回 event = {from:backbutton、 navigateBack} ，backbutton 表示来源是左上角返回按钮或 android 返回键
   * navigateBack表示来源是 uni.navigateBack ；
   * 支付宝小程序只有真机能触发，只能监听非navigateBack引起的返回，不可阻止默认行为。
   * app、H5、支付宝小程序
   */
  //onBackPress() {},
  // 监听原生标题栏搜索输入框输入内容变化事件 App、H5
  //onNavigationBarSearchInputChanged() {},
  // 监听原生标题栏搜索输入框搜索事件，用户点击软键盘上的“搜索”按钮时触发。App、H5
  //onNavigationBarSearchInputConfirmed() {},
  // 监听原生标题栏搜索输入框点击事件（pages.json 中的 searchInput 配置 disabled 为 true 时才会触发）App、H5
  //onNavigationBarSearchInputClicked() {},
  // 监听用户点击右上角转发到朋友圈 微信小程序
  //onShareTimeline() {},
  // 监听用户点击右上角收藏 微信小程序、QQ小程序
  //onAddToFavorites() {},
};
</script>
<style lang="scss" scoped>
view,
image {
  max-width: none;
}
.full-open-wrap {
  position: relative;
  width: 100vw;
  min-height: 100vh;
  background-color: #1b2e5d;

  .good-main {
    position: sticky;
    top: 0;
    width: 100%;
    min-height: 960rpx;
  }
  .goods-group {
    position: relative;
    z-index: 6;
    width: 100%;
    min-height: 600rpx;
  }
}
.timeout {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100074;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.7);
  .time-card {
    position: relative;
    width: 418rpx;
    height: 562rpx;
    .img-time {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    .time-content {
      position: relative;
      z-index: 1;
      width: 100%;
      height: 100%;
      .todo {
        position: absolute;
        bottom: 102rpx;
        width: 100%;
        left: 0;
        text-align: center;
        font-size: 22rpx;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #f4fc0e;
      }
      .know-btn {
        position: absolute;
        bottom: 10rpx;
        left: calc(50% - 100rpx);
        width: 200rpx;
        image {
          width: 100%;
        }
        // height: 126rpx;
      }
    }
  }
}
</style>
